package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import sun.security.provider.MD5;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Override
    public R<Employee> login(Employee employee) {
        //判断用户名是否存在
        Employee dbemployee = employeeMapper.login(employee);
        if(dbemployee==null){
            throw new BusinessException("用户名不存在");
       }
        String md5 = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if(!dbemployee.getPassword().equals(md5)){
            throw new BusinessException("用户名或者密码错误");
        }
        if(dbemployee.getStatus()==0){
            throw new BusinessException("你的账户已被禁用，请联系管理员解决");
        }
        return R.success(dbemployee);
    }

    @Override
    public Boolean save(Employee employee) {
        Employee dbEmployee = employeeMapper.login(employee);
        if(dbEmployee!=null){
            throw new BusinessException("当前用户已被注册");
        }
        String md5Password=DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(md5Password);
        employee.setStatus(1);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateTime(LocalDateTime.now());
        Integer num = employeeMapper.save(employee);
        return num>0;
    }

    @Override
    public Page<Employee> findByPage(Integer currentPage, Integer pageSize, String name) {

        PageHelper.startPage(currentPage, pageSize);
        List<Employee> pageData = employeeMapper.findByPage(name);

        PageInfo<Employee> EmployeePageInfo = new PageInfo<>(pageData);

        Page<Employee> page = new Page<>();
        page.setRecords(EmployeePageInfo.getList());
        page.setTotal(EmployeePageInfo.getTotal());
        return page;
    }

    @Override
    public R<Employee> findById(Integer id) {
        Employee emp = employeeMapper.findById(id);

        return R.success(emp);
    }

    @Override
    public Boolean update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        return employeeMapper.update(employee)>0;
    }
}